package cn.sdhuijin.service;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.sdhuijin.dao.BranchDao;
import cn.sdhuijin.dao.LoanOperateHistoryDao;
import cn.sdhuijin.dao.OfficialLoanDao;
import cn.sdhuijin.dao.UserDao;
import cn.sdhuijin.model.Branch;
import cn.sdhuijin.model.LoanOperateHistory;
import cn.sdhuijin.model.OfficialLoan;
import cn.sdhuijin.model.User;
import cn.sdhuijin.utils.ConstantStr;

/**
 * @author houyc
 *
 */
@Service
@Transactional
public class LoanServiceImpl implements LoanService {

	@Inject
	private OfficialLoanDao officialLoanDao;
	@Inject
	private LoanOperateHistoryDao loanOperateHistoryDao;
	@Inject
	private BranchDao branchDao;
	@Inject
	private UserDao userDao;

	@Override
	public Page<OfficialLoan> ListApplyInfo(int start, int limit,
			final String customName, final String startDate,
			final String endDate, final String status, final String telephone) {
		int page = start / limit;
		return officialLoanDao.findAll(new Specification<OfficialLoan>() {
			@Override
			public javax.persistence.criteria.Predicate toPredicate(
					Root<OfficialLoan> root, CriteriaQuery<?> query,
					CriteriaBuilder cb) {
				Path<String> loanApplyDate = root.get("applyDate");
				Path<String> loanName = root.get("customName");
				Path<String> loanStatus = root.get("status");
				Path<String> loanManagerTel = root.get("managerTel");
				query.where(cb.like(loanName, "%" + customName + "%"),
						cb.between(loanApplyDate, startDate, endDate),
						cb.like(loanStatus, "%" + status + "%"),
						cb.like(loanManagerTel, telephone));
				return null;
			}
		}, new PageRequest(page, limit, new Sort(Direction.DESC,
				new String[] { "applyDate" })));
	}

	@Override
	public OfficialLoan searchOne(String selectId) {
		Long id = Long.parseLong(selectId);
		return officialLoanDao.findOne(id);
	}

	@Override
	public boolean saveCustomApplyInfo(OfficialLoan loan) {
		boolean result = false;
		loan = officialLoanDao.save(loan);
		LoanOperateHistory history = new LoanOperateHistory();
		history.setApplyId(String.valueOf(loan.getId()));
		history.setApplyType(ConstantStr.APPLY_LOAN_TYPE_OFFICIAL);
		history.setOperateDate(loan.getApplyDate());
		history.setOperateName("提交申请");
		history.setRemarks(loan.getCustomName() + "提交贷款申请");
		history.setCurrentState(loan.getStatus());
		loanOperateHistoryDao.save(history);
		result = true;
		return result;
	}

	@Override
	public boolean saveRecallOperateHistory(String applyId, String applyType,
			String remarks, String opetateDate, String operateName,
			String currentState) {
		boolean result = false;
		OfficialLoan officialLoan = officialLoanDao.findOne(Long
				.parseLong(applyId));
		officialLoan.setStatus(currentState);
		officialLoanDao.save(officialLoan);
		LoanOperateHistory history = new LoanOperateHistory();
		history.setApplyId(applyId);
		history.setApplyType(applyType);
		history.setOperateDate(opetateDate);
		history.setOperateName(operateName);
		history.setRemarks(remarks);
		history.setCurrentState(currentState);
		loanOperateHistoryDao.save(history);
		result = true;
		return result;
	}

	@Override
	public boolean saveSuccessOperateHistory(String applyId, String applyType,
			String remarks, String opetateDate, String operateName,
			String currentState) {
		boolean result = false;
		OfficialLoan officialLoan = officialLoanDao.findOne(Long
				.parseLong(applyId));
		officialLoan.setStatus(currentState);
		officialLoanDao.save(officialLoan);
		LoanOperateHistory history = new LoanOperateHistory();
		history.setApplyId(applyId);
		history.setApplyType(applyType);
		history.setOperateDate(opetateDate);
		history.setOperateName(operateName);
		history.setRemarks(remarks);
		history.setCurrentState(currentState);
		loanOperateHistoryDao.save(history);
		result = true;
		return result;
	}

	@Override
	public boolean saveFailOperateHistory(String applyId, String applyType,
			String remarks, String opetateDate, String operateName,
			String currentState, String failReason) {
		boolean result = false;
		OfficialLoan officialLoan = officialLoanDao.findOne(Long
				.parseLong(applyId));
		officialLoan.setStatus(currentState);
		officialLoan.setFailReason(failReason);
		officialLoanDao.save(officialLoan);
		LoanOperateHistory history = new LoanOperateHistory();
		history.setApplyId(applyId);
		history.setApplyType(applyType);
		history.setOperateDate(opetateDate);
		history.setOperateName(operateName);
		history.setRemarks(remarks);
		history.setCurrentState(currentState);
		loanOperateHistoryDao.save(history);
		result = true;
		return result;
	}

	@Override
	public List<LoanOperateHistory> getOperateHistoryList(String applyId,
			String applyType) {
		Sort s = new Sort(Direction.DESC, "operateDate");
		return loanOperateHistoryDao.findByApplyIdAndApplyType(applyId,
				applyType, s);
	}

	@Override
	public boolean saveTransferOperateHistory(String applyId, String applyType,
			String remarks, String opetateDate, String operateName,
			String currentState, String branchId) {
		boolean result = false;
		OfficialLoan officialLoan = officialLoanDao.findOne(Long
				.parseLong(applyId));
		Branch branch = branchDao.findOne(Long.parseLong(branchId));
		officialLoan.setStatus(currentState);
		officialLoan.setBankId(Long.parseLong(branchId));
		officialLoan.setBankName(branch.getName());
		List<Long> branchIds = new ArrayList<Long>();
		branchIds.add(Long.parseLong(branchId));
		List<User> managerList = userDao.findByBranchIdInAndUserTypeLike(
				branchIds, ConstantStr.USER_TYPE_MANAGER + "%");
		User manager = null;
		if (managerList != null && managerList.size() > 0) {
			// 获取贷款额度最少的客户经理信息，待完善
			manager = managerList.get(0);
			officialLoan.setManagerId(manager.getId());
			officialLoan.setManagerName(manager.getName());
			officialLoan.setManagerTel(manager.getTelphone());
		}
		officialLoanDao.save(officialLoan);
		LoanOperateHistory history = new LoanOperateHistory();
		history.setApplyId(applyId);
		history.setApplyType(applyType);
		history.setOperateDate(opetateDate);
		history.setOperateName(operateName);
		history.setRemarks(remarks);
		history.setCurrentState(currentState);
		loanOperateHistoryDao.save(history);
		result = true;
		return result;
	}

	@Override
	public List<OfficialLoan> searchCustomApplyListByTelphone(String telphone) {
		return officialLoanDao.findByTelphoneOrderByApplyDateDesc(telphone);
	}

	@Override
	public boolean saveCustomEvaluateInfo(OfficialLoan loan) {
		boolean result = false;
		officialLoanDao.save(loan);
		result = true;
		return result;
	}
}
